package main

/*
#include <stdio.h>

void hi(char * str) {
    printf("hello world! %s\n",str);
}
*/
import "C"
import (
	"context"
	"fmt"
	"sync"
	"time"
)

var wg = sync.WaitGroup{}

func main() {
	/*fmt.Println("haha")
	s:="lalala"
	cs:=C.CString(s)
	//defer C.free(unsafe.Pointer(cs))
	C.hi(cs)*/
	/*	exitChan := make(chan int)
		con:=context.WithValue(context.TODO(),"a",1)
		fmt.Println(con.Value("a"))
		return*/
	//exitChan := make(chan int)

	/*wg.Add(2)
	var ctx context.Context
	var cancel context.CancelFunc
	ctx, cancel = context.WithCancel(context.Background())
	defer func() {
		fmt.Println("111111111111111")
		cancel()
	}()
	Attend(ctx)
	wg.Wait()*/
	solo := make(chan bool)
	for i := 0; i < 10; i++ {
		go doWork(i)
	}
	select {
	case <-solo:

	}
}

func doWork(i int) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(time.Second*5))
	defer func() {
		fmt.Println("this is over")
		fmt.Println("----------------------------")
		cancel()
	}()
	workChan := make(chan bool)
	go func(workChan chan bool) {
		defer func() {
			workChan <- true
		}()
		time.Sleep(time.Second * time.Duration(i))
	}(workChan)

	select {
	case <-ctx.Done():
		fmt.Println("time is out")
	case <-workChan:
		fmt.Println("work is done")
	}
}

func Attend(ctx context.Context) {
	ctxDeadLine, cancel := context.WithDeadline(ctx, time.Now().Add(time.Second*5))
	defer func() {
		fmt.Println("6666666")
		cancel()
	}()
	var isDone = make(chan bool)
	time.Sleep(time.Second * 1)
	go next(ctxDeadLine, isDone)
	select {
	case <-ctxDeadLine.Done():
		fmt.Println("time is over 1!")
		wg.Done()
	case <-isDone:
		fmt.Println("work done")
	}
	//isDone<-true

}

func next(ctx context.Context, isDone chan bool) {
	c_ctx, _ := context.WithDeadline(ctx, time.Now().Add(time.Second*2))
	go next_1(c_ctx)
	select {
	case <-c_ctx.Done():
		fmt.Println("老子结束了0")
		wg.Done()
		return
	}

	//isDone<-true
	/*defer func() {
		fmt.Println("next is over")
		cancel()
	}()*/
}

func next_1(ctx context.Context) {
	select {
	case <-ctx.Done():
		fmt.Println("老子结束了1")
		return
	}
}
